package io.xxx.mario.wechaty;

import com.alibaba.fastjson2.JSON;
import okhttp3.*;
import org.springframework.data.util.Pair;
import org.springframework.http.HttpMethod;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class RobotClient {

    private final MediaType mediaType = MediaType.parse("application/json");

    private final OkHttpClient httpClient;

    private final String host;

    private final Integer port;

    public RobotClient(String host, Integer port, OkHttpClient httpClient) {
        this.host = host;
        this.port = port;
        this.httpClient = httpClient;
    }

    public <T extends RobotRequest<R>, R extends RobotResponse> R execute(T request) {
        List<Pair<Integer, String>> errors = request.validate();
        if (!ObjectUtils.isEmpty(errors)) {
            throw new RobotException(errors);
        }

        HttpUrl.Builder urlBuilder = new HttpUrl.Builder()
                .host(host)
                .port(port)
                .encodedPath("/robot/getQRcode");
        request.queryParams()
                .forEach((name, value) -> urlBuilder.addQueryParameter(name, value == null ? "" : value.toString()));
        Request.Builder requestBuilder = new Request.Builder()
                .url(urlBuilder.build());
        if (request.httpMethod() == HttpMethod.GET) {
            requestBuilder.get();
        }
        if (request.httpMethod() == HttpMethod.POST) {
            Map<String, Object> body = request.body();
            RequestBody requestBody = RequestBody.create(JSON.toJSONString(body), mediaType);
            requestBuilder.post(requestBody);
        }

        Request req = requestBuilder.build();
        try (Response resp = httpClient.newCall(req).execute()) {
            ResponseBody body = resp.body();
            if (body != null) {
                return JSON.parseObject(body.string(), request.responseType());
            }
            throw new RobotException("Robot响应异常");
        } catch (IOException e) {
            throw new RobotException(e.getLocalizedMessage());
        }
    }
}
